package org.itboys.mobile.service.mysql.web;

import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.tools.AdminSessionHolder;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.TianJieWalletRecordMapper;
import org.itboys.mobile.dao.selling.TianJieSellingRewardMapper;
import org.itboys.mobile.entity.mongo.TianJieMember;
import org.itboys.mobile.entity.mysql.TianJieWallet;
import org.itboys.mobile.entity.mysql.TianJieWalletBlockRecord;
import org.itboys.mobile.entity.mysql.TianJieWalletRecord;
import org.itboys.mobile.entity.mysql.TianJieWalletReleaseRecord;
import org.itboys.mobile.entity.mysql.selling.TianJieSellingReward;
import org.itboys.mobile.service.mongo.web.TianJieMemberService;
import org.itboys.mysql.service.BaseMySqlService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：天街_消费卡_service
 */
@Service
public class TianJieWalletService extends BaseMySqlService<TianJieWallet> {
    @Autowired
    private TianJieWalletRecordMapper walletRecordMapper;
    @Autowired
    private TianJieSellingRewardMapper sellingRewardMapper;
    @Autowired
    private TianJieMemberService memberService;

    /**
     * 获取提现交易记录
     * @param request
     * @param accountStatuses 提现状态 1申请中，2，已通过，3已驳回
     * @return
     */
       public PageResult<TianJieWalletRecord> selectAccountRecord(HttpServletRequest request,List<Integer> accountStatuses){
        Map<String,Object> param = ParamUtil.packageMongoExactParam(request,"type");
        param.put("accountStatuses",accountStatuses);
        param.put("type",10);
        List<TianJieWalletRecord> result = walletRecordMapper.select(param);
        Serializable count =walletRecordMapper.count(param);
        //匹配用户信息
        List<Long> memberIds = new ArrayList<>();
        for(TianJieWalletRecord walletRecord:result){
            memberIds.add(walletRecord.getMemberId());
        }
        if(ListUtil.isNotNull(memberIds)){
            param.clear();
            param.put("id in",memberIds);
            List<TianJieMember> members = memberService.list(param);
            for(TianJieWalletRecord walletRecord:result){
                for(TianJieMember member:members){
                    if(LongUtil.isNotZreo(walletRecord.getMemberId())&&
                            walletRecord.getMemberId().longValue()==member.getId()){
                        walletRecord.setMemberName(member.getNickName());
                        walletRecord.setMemberMobile(member.getUserName());
                        break;
                    }

                }
            }
        }
        return new PageResult<TianJieWalletRecord>(result,count==null?0:Long.valueOf(count.toString()));
    }

    /**
     *获取全部交易记录（按用户）
     * @param request
     * @param memberId
     * @return
     */
    public PageResult<TianJieWalletRecord> selectMemberRecord(HttpServletRequest request,Long memberId){
        Map<String,Object> param = ParamUtil.packageMysqlPageParam(request,"");
        param.put("status",SundayCommonConstants.YES);
        List<TianJieWalletRecord> result = walletRecordMapper.select(param);
        Serializable count =walletRecordMapper.count(param);
        //匹配用户信息
        List<Long> memberIds = new ArrayList<>();
        for(TianJieWalletRecord walletRecord:result){
            memberIds.add(walletRecord.getMemberId());
        }
        if(ListUtil.isNotNull(memberIds)){
            param.clear();
            param.put("id in",memberIds);
            List<TianJieMember> members = memberService.list(param);
            for(TianJieWalletRecord walletRecord:result){
                for(TianJieMember member:members){
                    if(LongUtil.isNotZreo(walletRecord.getMemberId())&&
                            walletRecord.getMemberId().longValue()==member.getId()){
                        walletRecord.setMemberName(member.getNickName());
                        walletRecord.setMemberMobile(member.getUserName());
                        break;
                    }

                }
            }
        }
        return new PageResult<TianJieWalletRecord>(result,count==null?0:Long.valueOf(count.toString()));
    }
    /**
     * 通过用户寻找消费卡钱包
     * @param memberId
     * @return
     */
    @Transactional
    public TianJieWallet findByMemberId(Long memberId ){
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("memberId", memberId);
        TianJieWallet wallet=null;
        List<TianJieWallet> wallets=super.select(param);
        if(ListUtil.isNotNull(wallets)){
            wallet=wallets.get(0);
        }else {
            wallet=new TianJieWallet(memberId);
            super.insert(wallet);
            wallet=super.find(wallet.getId());
        }
        return wallet;
    }



    /**
     * 处理提现申请
     * @param recordId
     * @param isAgree
     * @param remark
     */
    @Transactional
    public void record_handle(Long recordId,boolean isAgree,String remark){
        Long loginUserId = AdminSessionHolder.getAdminUserId();
        if(!LongUtil.isNotZreo(loginUserId)){
            throw new ErrorException("登录信息已失效，请重新登陆");
        }
        TianJieWalletRecord record = walletRecordMapper.find(recordId);
        if(record.getAccountStatus()!=SundayCommonConstants.wallet_record_cash_status_apply){
            throw new ErrorException("申请记录状态错误，请刷新后重试。");
        }
        //已提现
        if(isAgree){
            record.setAccountStatus(SundayCommonConstants.wallet_record_cash_status_ytg);
            record.setRemark("提现已打款,备注："+remark);
            walletRecordMapper.update(record);
        //拒绝提现
        }else{
            record.setAccountStatus(SundayCommonConstants.wallet_record_cash_status_ybh);
            record.setRemark("提现已驳回,备注："+remark);
            walletRecordMapper.update(record);

            //更改用户消费卡主体
            TianJieWallet  wallet=findByMemberId(record.getMemberId());
            //2017年12月11日，更新
            if(record.getAccountCashAmount()!=null){
                wallet.setCashAmount(wallet.getCashAmount().add(record.getAccountCashAmount()));
            }
            if(record.getAccountReleaseAmount()!=null){
                wallet.setReleaseAmount(wallet.getReleaseAmount().add(record.getAccountReleaseAmount()));
            }
            if(record.getAccountProfitAmount()!=null){
                wallet.setProfitAmount(wallet.getProfitAmount().add(record.getAccountProfitAmount()));
            }

            super.update(wallet);
        }
    }


    /**
     * 虚拟充值。不产生提成和释放计划
     * 不产生余额，不产生提成，不产生释放计划
     * @param memberId
     * @param chargeAmount
     */
    @Transactional
    public void charge(long memberId,BigDecimal chargeAmount) {
        Long loginUserId = AdminSessionHolder.getAdminUserId();
        if(!LongUtil.isNotZreo(loginUserId)){
            throw new ErrorException("登录信息已失效，请重新登陆");
        }
        /********** ****************开始进行业绩分成***********************/
        logger.info("虚拟充值-开始业绩分成");
        /**
         *  只增加业绩，不增加现金
         */
        TianJieMember member = memberService.getById(memberId);
        //第二步，获取所有的提成比例配置信息。从底到高
        Map<String,Object> param = new HashMap<String,Object>();
        List<TianJieSellingReward> rewards = sellingRewardMapper.select(param);
        BigDecimal topScale=rewards.get(rewards.size()-1).getScale();

        //最高星级经理提出比例

        logger.info("--虚拟充值---开始业绩分成--------------最高等级折扣--"+topScale);

        //推荐链ID集合。包含自己的ID
        logger.info("---------"+member.getFinanceTjPath());
        List<String> tjIdsStr = Arrays.asList(member.getFinanceTjPath().split("/"));
        List<Long> tjIds = new ArrayList<>();
        for(String tjIdStr:tjIdsStr){
            logger.info("------tjIdStr====="+String.valueOf(tjIdStr));
            tjIds.add(Long.valueOf(tjIdStr));
        }
        param.clear();
        //查询推荐链上的钱包（内含分成折扣）。按折扣比例，从小到大
        param.put("memberIds",tjIds);
        param.put("sort_name","scale");
        param.put("sort_order","ASC");
        List<TianJieWallet> tjWaltes =super.select(param);
        //  logger.info("-------tjMembers=="+tjMembers.size());
        /**
         *  1，结算业务分成。按本次充值金额。
         * 1.1，结算分成比例达到最高比例，结束分成
         * 1.2，结算分成达到推荐链最后一人，结束分成
         */
        BigDecimal zero = new BigDecimal("0");

        for(int i=0;i<tjWaltes.size();i++){
            //本次循环的钱包
            TianJieWallet thisTjWalte = tjWaltes.get(i);
            //BigDecimal scale=null;
            //BigDecimal scaleAmount=null;
            //如果钱包被冻结。不参与业绩分成
            if(thisTjWalte.getStatus()!=1){
                logger.info("---虚拟充值--开始业绩分成----当前用户钱包被冻结--钱包ID"+thisTjWalte.getId());
                continue;
            }
            thisTjWalte.setTotalAchievement(thisTjWalte.getTotalAchievement().add(chargeAmount));
            logger.info("--虚拟充值---开始业绩分成-用户ID="+thisTjWalte.getMemberId()+"增加业绩="+chargeAmount);
            super.update(thisTjWalte);
        }
        logger.info("虚拟充值-结束业绩分成");
        logger.info("虚拟充值-开始业绩叠加");
        /**
         * 1，所有下线推荐人的业绩。匹配用户等级
         * 2，所有一级推荐人的业绩。匹配星级经理
         */
        logger.info("开始业绩叠加，更改用户等级");
        param.clear();
        param.put("id in",tjIds);
        List<TianJieMember> tjMembers = memberService.list(param);
        //查询的用户信息包括用户的第一级推荐的会员
        List<String> tjFirstIdsStr=new ArrayList<>();
        List<Long> tjFirstIds=new ArrayList<>();
        for(TianJieMember tjMember:tjMembers){
            if(StringUtils.isNotEmpty(tjMember.getFinanceTjFirstPath())){
                tjFirstIdsStr.addAll(Arrays.asList(tjMember.getFinanceTjFirstPath().split("/")));
            }
        }
        if(ListUtil.isNull(tjFirstIdsStr))return;
        //重新查询用户
        for(String tjFirstIdStr:tjFirstIdsStr){
            tjFirstIds.add(Long.valueOf(tjFirstIdStr));
        }
        param.clear();
        //推荐链上的用户的第一级推荐人的钱包
        param.put("memberIds",tjFirstIds);
        List<TianJieWallet> tjFirstWallets = super.select(param);

        //
        for(TianJieWallet tjWalte:tjWaltes){
            logger.info("推荐链，钱包Id="+tjWalte.getId()+"-用户Id"+tjWalte.getMemberId());
        }
        for(TianJieWallet tjFirstWallet:tjFirstWallets){
            logger.info("推荐第一级链，钱包Id="+tjFirstWallet.getId()+"-用户Id"+tjFirstWallet.getMemberId());
        }
        //  if(1==1)return;


        //用户等级提成中中，最高提成比例
        BigDecimal topGradeScale=new BigDecimal("0");
        //等级折扣奖励
        List<TianJieSellingReward> gradeRewards = new ArrayList<>();
        //星级折扣奖励
        List<TianJieSellingReward> starRewards = new ArrayList<>();
        //星级折扣达标金额。要求维护的达标星级金额是一样
        BigDecimal starAchievement = null;
        for(TianJieSellingReward reward:rewards){
            if(reward.getType()==1){
                gradeRewards.add(reward);
                if(reward.getScale().compareTo(topGradeScale)==1){
                    topGradeScale=reward.getScale();
                }
            }else if(reward.getType()==2){
                starRewards.add(reward);
                starAchievement=reward.getAmount();
            }
        }
        //  logger.info("000000000000000000000000======"+rewards.size());

        //  return;
        //先把第一梯队的推荐人信息写入到钱包中
        for(TianJieWallet tjWalte:tjWaltes){
            for(TianJieMember tjMember:tjMembers){
                if(LongUtil.isNotZreo(tjWalte.getMemberId())&&
                        tjWalte.getMemberId().longValue()==tjMember.getId()){
                    tjWalte.setFinanceTjFirstPath(tjMember.getFinanceTjFirstPath());
                    break;
                }
            }
        }

        /*if(1==1){
            return;
        }*/
        /**
         * 判断逻辑
         * 1，用户已经是星级折扣。只判断星级折扣
         * 2，用户已经是等级折扣，先判断等级折扣，再判断星级折扣
         * 3，用户已经是最高提成比例，退出判断
         */
        //判断等级折扣
        for(TianJieWallet tjWalte:tjWaltes){
            if(tjWalte.getStatus()!=1){
                logger.info("----开始业绩叠加----当前用户钱包被冻结--钱包ID"+tjWalte.getId());
                continue;
            }
            //新的折扣
            BigDecimal newScale= tjWalte.getScale();
            /*********************如果用户已经星级折扣，不再判断等级折扣***********/
            if(tjWalte.getScale().compareTo(topGradeScale)==1){
                logger.info("开始业绩叠加，更改用户等级-已是星级折扣，用户ID="+tjWalte.getMemberId());
                logger.info("当前最高星级折扣="+topScale+",当前星级最高业绩="+starAchievement);
                //如果该用户没有任何的第一推荐人
                if(StringUtils.isEmpty(tjWalte.getFinanceTjFirstPath())){
                    logger.info("开始业绩叠加，更改用户等级-已是星级折扣-没有一级团队，用户ID="+tjWalte.getMemberId());
                    continue;
                }

                //当前用户的第一级推荐的达标数量
                int starNumber=0;
                //当前用户的第一级推荐人钱包
                //获取达标的团队数量
                for(TianJieWallet tjFirstWallet:tjFirstWallets){
                    if(tjWalte.getFinanceTjFirstPath().contains(tjFirstWallet.getMemberId().toString())&&
                            tjFirstWallet.getTotalAchievement().compareTo(starAchievement)==1){
                        starNumber++;
                    }
                }

                //根据达标的团队数量，更新等级。算法1：按等于
                        /*for (TianJieSellingReward starReward : starRewards) {
                            if (starNumber == starReward.getNumber()) {
                                newScale = starReward.getScale();
                                break;
                            }
                        }*/
                //根据达标的团队数量，更新等级。算法2：按大于
                for (TianJieSellingReward starReward : starRewards) {
                    if (starNumber >= starReward.getNumber()) {
                        newScale = starReward.getScale();

                    }
                }
                logger.info("开始业绩叠加，更改用户等级-已是星级折扣，达标团队数量="+starNumber+"新折扣="+newScale+"用户ID="+tjWalte.getMemberId());
                //根据达标的团队数量，更新等级。算法2：按大于
               /* for(TianJieSellingReward starReward:starRewards){
                    if(starNumber>=starReward.getNumber()){
                        newScale=starReward.getScale();
                    }
                }*/

                /*********************用户已经是等级折扣，先判断等级折扣，再判断星级折扣***********/
                /** 假代码
                 * 新的等级折扣=算出结果。
                 *
                 * if(新的等级折扣>最高等级折扣){
                 *      判断星级折扣
                 * }
                 */
            }else {
                logger.info("开始业绩叠加，更改用户等级-已是等级折扣，用户ID=" + tjWalte.getMemberId());

                //算出新的等级折扣
                for (TianJieSellingReward gradeReward : gradeRewards) {
                    //循环迭代出最大的折扣
                    if (tjWalte.getTotalAchievement().compareTo(gradeReward.getAmount()) == 1) {
                        newScale = gradeReward.getScale();
                    }
                }
                logger.info("开始业绩叠加，更改用户等级-已是等级折扣，新折扣=" + newScale + "用户ID=" + tjWalte.getMemberId());
                //如果本次已经到达的最高的等级折扣，才判断星级折扣
                //一级团队必须有值
                if (newScale.compareTo(topGradeScale) != -1 && StringUtils.isNotEmpty(tjWalte.getFinanceTjFirstPath())) {
                    logger.info("开始业绩叠加，更改用户等级-达到最高等级折扣，进入星级折扣判断,用户ID=" + tjWalte.getMemberId() + "当前折扣=" + newScale);
                    int starNumber = 0;
                    //获取达标的团队数量
                    for (TianJieWallet tjFirstWallet : tjFirstWallets) {
                        if (tjWalte.getFinanceTjFirstPath().contains(tjFirstWallet.getMemberId().toString()) &&
                                tjFirstWallet.getTotalAchievement().compareTo(starAchievement) == 1) {
                            starNumber++;
                        }
                    }
                    //根据达标的团队数量，更新等级。算法1：按等于
                        /*for (TianJieSellingReward starReward : starRewards) {
                            if (starNumber == starReward.getNumber()) {
                                newScale = starReward.getScale();
                                break;
                            }
                        }*/
                    //根据达标的团队数量，更新等级。算法2：按大于
                    for (TianJieSellingReward starReward : starRewards) {
                        if (starNumber >= starReward.getNumber()) {
                            newScale = starReward.getScale();

                        }
                    }
                    logger.info("开始业绩叠加，更改用户等级-达到最高等级折扣-进入星级折扣，达标团队数量="+starNumber+"新折扣="+newScale+"用户ID="+tjWalte.getMemberId());
                }
            }


            logger.info("业绩叠加结束。用户ID="+tjWalte.getMemberId()+",钱包ID="+tjWalte.getId()+",新折扣="+newScale+",旧折扣="+tjWalte.getScale());
            //更新提成比例
            if(newScale.compareTo(tjWalte.getScale())==1){
                tjWalte.setScale(newScale);
                super.update(tjWalte);
            }
        }
        logger.info("虚拟充值-结束业绩叠加");
        logger.info("虚拟充值-结束充值");

    }


}
